package com.imiku.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imiku.utils.QiniuUtils;
import com.imiku.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadFileController {

    @Autowired
    private QiniuUtils qiniuUtils;

    /**
     * 上传文件到七牛云存储
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @RequestMapping("/img/qiniu")
    public String uploadImgQiniu(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
        String path = qiniuUtils.uploadImg(inputStream, UUIDUtils.getUUID32());
        JSONObject jsonObject = new JSONObject(true);
        jsonObject.put("code", 1);
        jsonObject.put("src", path);
        return jsonObject.toJSONString();
    }

    @RequestMapping("/cover/qiniu")
    public String coverImgUpload(@RequestParam("file") MultipartFile[] multipartFile) throws IOException {
        JSONArray jsonArray = new JSONArray();
        for (MultipartFile mufile: multipartFile) {
            FileInputStream inputStream = (FileInputStream) mufile.getInputStream();
            String path = qiniuUtils.uploadImg(inputStream, UUIDUtils.getUUID32());
            JSONObject fileJson = new JSONObject(true);
            fileJson.put("url", path);
            fileJson.put("name", path.substring(path.lastIndexOf("/") + 1, path.length()));
            jsonArray.add(fileJson);
        }
        return jsonArray.toJSONString();
    }

}
